/*
 * Created: Author: Aléx Carvalho / Date: Jan 23, 2015
 * 
 * Changed: $Author: ac280593@gmail.com $ / $Date: 2015-05-15 00:29:31 +0000 (Fri, 15 May 2015) $
 */
package com.cpm.wrapper;

import com.cpm.aggregate.Attribute;
import com.cpm.context.SystemLogger;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Password implements Attribute<String> {

    @Column(length = 100, nullable = false)
    private String password;

    public Password() {
    }

    /**
     *  A senha passada como parametro será automaticamente criptografada
     * @param passwordToEncrypt
     */
    public Password(String passwordToEncrypt) {
        this.password = encryptPassword(passwordToEncrypt);
    }

    /**
     *  A senha passada como parametro será automaticamente criptografada
     * @param passwordToEncrypt
     */
    public void setPassword(String passwordToEncrypt) {
        this.password = encryptPassword(password);
    }
    
    private synchronized String encryptPassword(String password) {
        String value = "";
        
        try {
            MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
            msgDigest.update(password.getBytes("UTF-8"));
            byte rawByte[] = msgDigest.digest();
            
            value = Base64.getEncoder().encodeToString(rawByte);
        }
        catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            SystemLogger.logException(e);
        }
        
        return value;
    }

    @Override
    public String getValue() {
        return password;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Password) {
            return this.password.equals( ((Password)obj).password );
        }
        
        return false;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 29 * hash + Objects.hashCode(this.password);
        return hash;
    }
}
